//
// Created by 14683 on 2021/10/5.
//
#include <FreeImage.h>
#include <jni.h>
#include "android_log.h"


extern "C"
JNIEXPORT jboolean JNICALL
Java_com_htt_image_FreeImageUtil_imageToBmp(
        JNIEnv *env,
        jobject thiz,
        jstring source_path,
        jstring out_path,
        jint width=240,
        jint height=320) {
    //初始化FreeImage
    FreeImage_Initialise(TRUE);
    LOGD("FreeImage Version:%s", FreeImage_GetVersion());

    const char *path = env->GetStringUTFChars(source_path, JNI_FALSE);
    const char *outPath = env->GetStringUTFChars(out_path, JNI_FALSE);

    int imageFormat = FreeImage_GetFIFFromFilename(path);
    LOGD("imageFormat=%d", imageFormat);
    FIBITMAP *bitmap = FreeImage_Load(static_cast<FREE_IMAGE_FORMAT>(imageFormat), path);
    if (bitmap == nullptr) {
        LOGE("load image failed!");
        return FALSE;
    }

    unsigned int imgWidth = FreeImage_GetWidth(bitmap);//获取图像的宽
    unsigned int imgHeight = FreeImage_GetHeight(bitmap);//获取图像的高
    LOGD("图片的大小：width=%d,height=%d", imgWidth, imgHeight);
    FIBITMAP *sizeBmp = FreeImage_Rescale(bitmap, width, height);
    FIBITMAP *convertBmp = nullptr;
    if (sizeBmp == nullptr){
        convertBmp = FreeImage_ConvertTo16Bits555(bitmap);
    }else{
        convertBmp=FreeImage_ConvertTo16Bits555(sizeBmp);
        FreeImage_Unload(sizeBmp);
    }
    BOOL result=TRUE;
    if(convertBmp== nullptr){
        result= FreeImage_Save(FIF_BMP,bitmap,outPath,BMP_DEFAULT);
    }else{
        result=FreeImage_Save(FIF_BMP,convertBmp,outPath,BMP_DEFAULT);
        FreeImage_Unload(convertBmp);
    }

    //释放加载的bitmap
    FreeImage_Unload(bitmap);

    //释放 FreeImage
    FreeImage_DeInitialise();
    return result;
}